package com.example.sharesinfo.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.androidkun.xtablayout.XTabLayout;
import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.PersonalCenterBean;
import com.example.sharesinfo.bean.SharesInfoBean;
import com.example.sharesinfo.bean.StockRealtimeBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.UIHelper;
import com.example.sharesinfo.model.SellOrBuyModel;
import com.example.sharesinfo.model.StocksCommentsModel;
import com.example.sharesinfo.utils.LineChartTools;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.InputTextMsgDialog;
import com.example.sharesinfo.view.NoScrollListview;
import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.util.Const;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import lecho.lib.hellocharts.view.LineChartView;

public class SharesInfoActivity extends BaseUIActivity implements View.OnClickListener {

    private static final int GetStockSuccess = 1001;
    private static final int GetStockFailed = 1002;
    private static final int GetStockDetailSuccess = 1003;
    private static final int GetStockDetailFailed = 1004;
    private static final int GetStockCommentSuccess = 1005;
    private static final int GetStockCommentFailed = 1006;
    private String nameOrcode;
    private LineChartView lineChart;
    private List<SharesInfoBean> heartList = new ArrayList<>();
    private AppBarLayout content;
    private TextView tv_stock_nowPrice;
    private TextView tv_diff_money;
    private TextView tv_diff_rate;
    private TextView tv_max;
    private TextView tv_low;
    private TextView tv_open;
    private TextView tv_turnover;
    private TextView tv_all_value;
    private TextView tv_tradeAmount;
    private TextView tv_time;
    private TextView tv_new;
    private TextView diff_rate;
    private TextView tv_stock_name;
    private TextView tv_stock_code;
    private RecyclerView rc_sell_buy;
    private List<SellOrBuyModel> mList = new ArrayList<>();
    private CommonAdapter<SellOrBuyModel> mAdapter;
    private Button btn_send_comment;
    private ImageButton ib_back;
    private InputTextMsgDialog inputTextMsgDialog;
    //评论 RecyclerView
    private RecyclerView mvNewsCommentsView;
    private CommonAdapter<StocksCommentsModel> mNewsCommentsAdapter;
    private List<StocksCommentsModel> mCommentsList = new ArrayList<>();
    //点赞和取消
    //TalkId=***&UserId=***
    private String SendNewsCommentPraise = "http://119.23.221.142/api/stock/SendStockCommentPraise?";
    private Map<String, String> praiseDatas = new HashMap<>();
    //TalkId=***&UserId=***
    private String CancelNewsCommentPraise = "http://119.23.221.142/api/stock/CancelStockCommentPraise?";
    private Map<String, String> CancelPraiseDatas = new HashMap<>();

    public static void startActivity(Context mContext, String nameOrcode) {
        Intent intent = new Intent(mContext, SharesInfoActivity.class);
        intent.putExtra("nameOrcode", nameOrcode);
        mContext.startActivity(intent);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case GetStockSuccess:
                    StockRealtimeBean result = (StockRealtimeBean) msg.obj;
                    for (int i = 0; i < result.getData().size(); i++) {
                        LogUtils.i("股价：" + Float.parseFloat(result.getData().get(i).getOpen()));
                        SharesInfoBean info = new SharesInfoBean(Float.parseFloat(result.getData().get(i).getOpen()), result.getData().get(i).getTime());
                        heartList.add(info);
                    }
                    tv_time.setText("时间:" + heartList.get(result.getData().size() - 1).getTime());
                    LineChartTools.setChartViewData(heartList, lineChart);
                    UIHelper.hideDialogForLoading();
                    content.setVisibility(View.VISIBLE);
                    break;
                case GetStockFailed:
                    break;
                case GetStockDetailSuccess:
                    JSONObject result1 = (JSONObject) msg.obj;
                    try {
                        JSONArray array = result1.getJSONArray("data");
                        JSONObject data = array.getJSONObject(0);
                        tv_stock_name.setText(data.getString("name"));
                        tv_stock_code.setText(data.getString("code"));
                        tv_stock_nowPrice.setText(data.getString("nowPrice"));
                        tv_diff_money.setText(data.getString("diff_money"));
                        tv_diff_rate.setText(data.getString("diff_rate"));
                        tv_max.setText(data.getString("todayMax"));
                        tv_low.setText(data.getString("todayMin"));
                        tv_open.setText(data.getString("openPrice"));
                        tv_turnover.setText(data.getString("turnover"));
                        tv_all_value.setText(data.getString("all_value"));
                        tv_tradeAmount.setText(data.getString("tradeAmount"));
                        //时间暂时没有设置
                        //tv_time.setText("时间:" + data.getString("nowPrice"));
                        tv_new.setText("最新:" + data.getString("nowPrice"));
                        diff_rate.setText("涨幅:" + data.getString("diff_rate"));
                        for (int i = 1; i <= 5; i++) {
                            SellOrBuyModel model = new SellOrBuyModel();
                            model.setName("买" + i);
                            String str = "buy" + i + "_n";
                            model.setNum(data.getString(str));
                            str = "buy" + i + "_m";
                            model.setPrice(data.getString(str));
                            mList.add(model);
                        }
                        for (int i = 1; i <= 5; i++) {
                            SellOrBuyModel model = new SellOrBuyModel();
                            model.setName("卖" + i);
                            String str = "sell" + i + "_n";
                            model.setNum(data.getString(str));
                            str = "sell" + i + "_m";
                            model.setPrice(data.getString(str));
                            mList.add(model);
                        }
                        mAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case GetStockDetailFailed:
                    break;
                case GetStockCommentSuccess:
                    JSONArray array = (JSONArray) msg.obj;
                    LogUtils.i("查询成功");
                    if (mCommentsList.size() > 0) {
                        mCommentsList.clear();
                    }
                    for (int i = 0; i < array.length(); i++) {
                        try {
                            JSONObject object = array.getJSONObject(i);
                            StocksCommentsModel model = new StocksCommentsModel();
                            model.setId(Integer.parseInt(object.getString("Id")));
                            model.setUserId(Integer.parseInt(object.getString("UserId")));
                            model.setUserName(object.getString("Username"));
                            model.setComment_If_Praise(object.getString("If_Praise"));
                            model.setCommentTime(object.getString("CommentTime"));
                            model.setComment_PraiseNumber(object.getString("PraiseNumber"));
                            model.setImageUrl(object.getString("ImageUrl"));
                            model.setPoint(object.getString("Point"));
                            LogUtils.i("UserId:" + object.getString("UserId"));
                            mCommentsList.add(model);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    LogUtils.i("UserId:" + mCommentsList.size());
                    mvNewsCommentsView.setVisibility(View.VISIBLE);
                    mNewsCommentsAdapter.notifyDataSetChanged();
                    break;
                case GetStockCommentFailed:
                    break;
                case 404:
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shares_info);
        initView();
        nameOrcode = getIntent().getStringExtra("nameOrcode");
        UIHelper.showDialogForLoading(this, "数据加载中...");
        getOneStockRealtimeQuotation(nameOrcode);
        getOneStockDetail(nameOrcode);
        GetStockCommentsList(nameOrcode);
    }


    private void initView() {
        ib_back = findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        tv_stock_name = findViewById(R.id.tv_stock_name);
        tv_stock_code = findViewById(R.id.tv_stock_code);
        content = findViewById(R.id.content);
        lineChart = findViewById(R.id.chart);
        tv_stock_nowPrice = findViewById(R.id.tv_stock_nowPrice);
        tv_diff_money = findViewById(R.id.tv_diff_money);
        tv_diff_rate = findViewById(R.id.tv_diff_rate);
        tv_max = findViewById(R.id.tv_max);
        tv_low = findViewById(R.id.tv_low);
        tv_open = findViewById(R.id.tv_open);
        tv_turnover = findViewById(R.id.tv_turnover);
        tv_all_value = findViewById(R.id.tv_all_value);
        tv_tradeAmount = findViewById(R.id.tv_tradeAmount);
        tv_time = findViewById(R.id.tv_time);
        tv_new = findViewById(R.id.tv_new);
        diff_rate = findViewById(R.id.diff_rate);
        btn_send_comment = findViewById(R.id.news_body_comment_box_btn);
        btn_send_comment.setOnClickListener(this);
        rc_sell_buy = findViewById(R.id.rc_sell_buy);

        rc_sell_buy.setLayoutManager(new LinearLayoutManager(this));
        rc_sell_buy.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        mAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<SellOrBuyModel>() {
            @Override
            public void onBindViewHolder(SellOrBuyModel model, CommonViewHolder viewHolder, int type, int position) {
                viewHolder.setText(R.id.name, model.getName());
                viewHolder.setText(R.id.num, model.getNum());
                viewHolder.setText(R.id.price, model.getPrice());
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_sell_or_buy_item;
            }
        });
        rc_sell_buy.setAdapter(mAdapter);

        mvNewsCommentsView = findViewById(R.id.rc_comments);
        mvNewsCommentsView.setLayoutManager(new LinearLayoutManager(this));
        mvNewsCommentsView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        mvNewsCommentsView.setFocusable(false);
        mNewsCommentsAdapter = new CommonAdapter<>(mCommentsList, new CommonAdapter.OnBindDataListener<StocksCommentsModel>() {
            @Override
            public void onBindViewHolder(final StocksCommentsModel model, final CommonViewHolder viewHolder, int type, int position) {
                final ImageView praised = viewHolder.getView(R.id.iv_news_comment_praised);
                if (praiseDatas.size() > 0) {
                    praiseDatas.clear();
                }
                if (CancelPraiseDatas.size() > 0) {
                    CancelPraiseDatas.clear();
                }
                if (!model.getComment_If_Praise().equals("False")) {
                    praised.setImageResource(R.drawable.praise_checked);
                    praised.setTag("checked");
                } else {
                    praised.setImageResource(R.drawable.praise_unchecked);
                    praised.setTag("unchecked");
                }
                final int[] praise = {Integer.parseInt(model.getComment_PraiseNumber())};
                praised.setOnClickListener(new View.OnClickListener() {
                    //点赞事件
                    @Override
                    public void onClick(View v) {
                        if (praised.getTag().equals("unchecked")) {
                            praised.setImageResource(R.drawable.praise_checked);
                            praise[0] += 1;
                            viewHolder.setText(R.id.tv_news_comment_praise_num, "" + praise[0]);
                            praised.setTag("checked");
                            //TalkId=***&UserId=***
                            praiseDatas.put("StockCommentId", String.valueOf(model.getId()));
                            praiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(SendNewsCommentPraise, null,
                                    praiseDatas, null, null,
                                    new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "点赞失败");
                                        }
                                    });
                        } else if (praised.getTag().equals("checked")) {
                            LogUtils.i("点赞事件处理" + "取消点赞");
                            praised.setImageResource(R.drawable.praise_unchecked);
                            praise[0] -= 1;
                            viewHolder.setText(R.id.tv_news_comment_praise_num, "" + praise[0]);
                            praised.setTag("unchecked");
                            //TalkId=***&UserId=***
                            CancelPraiseDatas.put("StockCommentId", String.valueOf(model.getId()));
                            CancelPraiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(CancelNewsCommentPraise, null,
                                    CancelPraiseDatas, null, null, new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "取消点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "取消点赞失败");
                                        }
                                    });

                        }
                    }
                });
                viewHolder.setImageUrl(SharesInfoActivity.this, R.id.tv_comment_head, model.getImageUrl());
                viewHolder.setText(R.id.news_body_comments_name, model.getUserName());
                viewHolder.setText(R.id.news_body_comments_content, model.getPoint());
                viewHolder.setText(R.id.news_body_comments_time, model.getCommentTime());
                viewHolder.setText(R.id.tv_news_comment_praise_num, model.getComment_PraiseNumber());

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_shares_comment_item;
            }
        });
        mvNewsCommentsView.setAdapter(mNewsCommentsAdapter);
        btn_send_comment = findViewById(R.id.news_body_comment_box_btn);
        btn_send_comment.setOnClickListener(this);
        inputTextMsgDialog = new InputTextMsgDialog(this, R.style.customdialogstyle);
        inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
            @Override
            public void onTextSend(String msg) {
                addComment(msg);
                Toast.makeText(SharesInfoActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                GetStockCommentsList(nameOrcode);
            }
        });
    }

    /**
     * 添加评论消息
     */
    private void addComment(String msg) {
        String url = "http://119.23.221.142/api/stock/SendStockComments?" +
                "StockCode=" + nameOrcode + "&UserId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "") + "&Point=" + msg;
        OkHttpUtils.getInstance().Post(url, null, null, null, null,
                new OkHttpUtils.okHttpListener() {
                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        LogUtils.i("评论：" + s);
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });
    }

    /**
     * 单支股票实时行情
     * GET
     * 参数 NameorCode=000001
     */
    private void getOneStockRealtimeQuotation(String nameOrcode) {
        String url = "http://119.23.221.142/api/stock/GetOneStockRealtimeQuotation?NameorCode=" + nameOrcode
                + "&UserId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i("testUrl:" + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    StockRealtimeBean bean = new Gson().fromJson(s, StockRealtimeBean.class);
                    message.what = GetStockSuccess;
                    message.obj = bean;
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetStockFailed;
                    mHandler.sendMessage(message);
                }
                LogUtils.i("实时股：" + s);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 股票详情（参数为NameorCode（股票名称或代码））
     * Get
     * 参数 NameorCode=000002
     */
    private void getOneStockDetail(String NameorCode) {
        String url = "http://119.23.221.142/api/stock/GetOneStockDetail?NameorCode=" + NameorCode + "&UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i("testUrl:" + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                LogUtils.i("SharesInfoActivity：" + s);
                if (object.getString("code").equals("200")) {
                    message.what = GetStockDetailSuccess;
                    message.obj = object;
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetStockDetailFailed;
                    mHandler.sendMessage(message);
                }

            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 股票详情（参数为NameorCode（股票名称或代码））
     * Get
     * 参数 StockCode=000002
     */
    private void GetStockCommentsList(String StockCode) {
        String url = "http://119.23.221.142/api/stock/GetStockCommentsList?StockCode=" + StockCode + "&UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i("testUrl:" + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    message.what = GetStockCommentSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetStockCommentFailed;
                    mHandler.sendMessage(message);
                }

            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.news_body_comment_box_btn:
                inputTextMsgDialog.show();
                break;
            case R.id.ib_back:
                finish();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIHelper.hideDialogForLoading();
    }
}
